<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\Form;
use My\Model\DistributionShopPackageModel;
use Think\Model;
use My\Model\GoodsModel;
use My\Model\DeliveryModel;

class DistributionShopPackageController extends BackgroundController {
	
	protected function _initialize() {
		$this->setControllerTitle('套餐管理');
		$this->setActionTitle(array(
			'index' => '套餐列表',
	        'add' => '添加套餐',
			'modify' => '编辑套餐'
		));
		$this->setActionNav(array(
			'index',
			'add'
		));
	}
	
	/**
	 * 套餐列表
	 */
	protected function getLists( $is_deleted ) {
		$page = $this->getPage ();
		$pagesize = $this->getPageSize ();
		$d = D ( 'DistributionShopPackage' );
		$params = array();
		$condition = array (
			'cid' => $this->aid,
			'isDeleted' => $is_deleted,
		);
		$distributionShopPackageList = $d->where ( $condition )->limit ( $pagesize )->page ( $page )->order ( 'id DESC' )->select ();
		$distributionShopPackageCount = $d->where ( $condition )->count ();
		$this->assign ( 'distributionShopPackageList', $distributionShopPackageList );
		$this->showPage ( $distributionShopPackageCount, $pagesize );
		$this->display();
	}
	
	/**
	 * 添加套餐
	 * @see \Utuo\BackgroundController::addAction()
	 */
	public function addAction() {
		$selected = array();
		$goodsList = M("DistributionShopGoods")->where(array('cid'=>$this->aid, 'status'=>1, 'is_deleted'=>0))->getField("id,name,price,status");
		$disShop = M("DistributionShop")->where(array("cid"=>$this->aid))->find();
		if ( $disShop and $disShop['agent_shop_config'] ) {
		    $disShop['agent_shop_config'] = unserialize($disShop['agent_shop_config']);
		    $agentLevel = $disShop['agent_shop_config']['level']*1;
		}
		$agentLevel = $agentLevel ? $agentLevel : 3;
		/* 默认套餐数据 */
		$distributionShopPackage = array(
		    'name' => '',
		    'shipping_method' => 0,
		    'shipping_tpl_id' => 0,
		    'image' => '',
		    'image_vertical' => '',
		    'image_share' => '',
		    'config' => array(),
		);

		/* 运费配置 */
		$distributionShopPackage['shipping_config'] = (object)array_fill_keys(array_keys(DeliveryModel::$METHOD), 0);
		
		/* 套餐基础配置 */
	    $distributionShopPackage['config']['base'] = array(
	        'discount' => array_fill(0, $agentLevel, 0),
	        'recommendBouns' => 0,
	        'recommendPercent' => '',
	    );
		/* 套餐配置  */
		foreach ( DistributionShopPackageModel::$packageTypes as $k => $v ) {
	        if ( $k === DistributionShopPackageModel::PACKAGE_TYPE_UPDATE ) {
	            if ( !isset($distributionShopPackage['config'][$k]) ) {
	                $distributionShopPackage['config'][$k] = array(
	                    'toLevel' => 0,
	                );
	            }
	        }
	    }
		$distributionShopPackage['config'] = (object)$distributionShopPackage['config'];
		
		/* 运费模板 */
		$deliveryTpl = M("DeliveryTpl")->where(array("cid" => $this->aid))->getField("id,name");
		$deliveryTplOptions = array( '0' => '==不使用运费模板==' );
		foreach ( $deliveryTpl as $k => $v ) $deliveryTplOptions[$k] = $v;
		$deliveryTplJson = json_encode((object)$deliveryTplOptions);
		
		/* 代理级数 */
		$levels = array();
	    for( $i=0; $i<$agentLevel; $i++) {
	        $levels[$i] = $i+1;
	    }
		$this->assign("agentLevelJson", json_encode((object)$levels));
		
		$this->assign("deliveryTplJson", $deliveryTplJson);
		$this->assign("shippingMethods", json_encode((object)GoodsModel::$SHIPPING_METHOD));
		$this->assign("deliveryMethods", DeliveryModel::$METHOD);
		$this->assign("goodsPackage", json_encode($distributionShopPackage));
		$this->assign("goodsList", json_encode($goodsList));
		$this->assign("packageTypesOptions", Form::getOption(DistributionShopPackageModel::$packageTypes, "", '==请选择套餐类型=='));
		$this->assign('selectedJson', json_encode($selected));
		$this->display('save');
	}
	
	/**
	 * 编辑套餐
	 * @see \Utuo\BackgroundController::addAction()
	 */
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$distributionShopPackage = M("DistributionShopPackage")->where(array('cid'=>$this->aid, 'id' => $id))->find();
		$disShop = M("DistributionShop")->where(array("cid"=>$this->aid))->find();
		if ( $disShop and $disShop['agent_shop_config'] ) {
		    $disShop['agent_shop_config'] = unserialize($disShop['agent_shop_config']);
		    $agentLevel = $disShop['agent_shop_config']['level']*1;
		}
		$agentLevel = $agentLevel ? $agentLevel : 3;
		if ( $distributionShopPackage ) {
		    /* 套餐商品 */
			$distributionShopPackage['goods'] = array();
			$goods = M("DistributionShopPackageGoods")->where("packageId=%d", $id)->field("goodsId as id,count")->select() and $distributionShopPackage['goods'] = $goods;
			/* 运费配置 */
			if ( $distributionShopPackage['shipping_config'] ) {
			    $distributionShopPackage['shipping_config'] = unserialize($distributionShopPackage['shipping_config']);
			} else {
			    $distributionShopPackage['shipping_config'] = array_fill_keys(array_keys(DeliveryModel::$METHOD), 0);
			}
			$distributionShopPackage['shipping_config'] = (object)$distributionShopPackage['shipping_config'];
			/* 套餐配置  */
		    if ( $distributionShopPackage['config'] ) {
		        $distributionShopPackage['config'] = unserialize($distributionShopPackage['config']);
		    } else {
		        $distributionShopPackage['config'] = array();
		    }
		    /* 基础配置 */
		    if ( empty($distributionShopPackage['config']['base']) ) {
		        $distributionShopPackage['config']['base'] = array(
		            'discount' => array_fill(0, $agentLevel, 0),
		            'recommendBouns' => 0,
		            'recommendPercent' => '',
		        );
		    }
		    /* 代理级数有变化时 */
		    $count = count($distributionShopPackage['config']['base']['discount']);
		    if ( $count < $agentLevel ) {
		        $distributionShopPackage['config']['base']['discount'] = array_pad($distributionShopPackage['config']['base']['discount'], $agentLevel, 0);
		    }
		    /* 附加配置 */
		    foreach ( DistributionShopPackageModel::$packageTypes as $k => $v ) {
		        if ( $k === DistributionShopPackageModel::PACKAGE_TYPE_UPDATE ) {
		            if ( !isset($distributionShopPackage['config'][$k]) ) {
		                $distributionShopPackage['config'][$k] = array(
		                    'toLevel' => 0,
		                );
		            } else {
		                if ( isset($distributionShopPackage['config'][$k]['discount']) ) {
		                    $distributionShopPackage['config']['base']['discount'] = $distributionShopPackage['config'][$k]['discount'];
		                    $distributionShopPackage['config']['base']['recommendBouns'] = $distributionShopPackage['config'][$k]['recommendBouns'];
		                    $distributionShopPackage['config']['base']['recommendPercent'] = $distributionShopPackage['config'][$k]['recommendPercent'];
		                    unset($distributionShopPackage['config'][$k]['discount']);
		                    unset($distributionShopPackage['config'][$k]['recommendBouns']);
		                    unset($distributionShopPackage['config'][$k]['recommendPercent']);
		                }
		            }
		        }
		    }
		    $distributionShopPackage['config'] = (object)$distributionShopPackage['config'];
		}
		$selected = array();
		if ( $goods ) {
			foreach ( $goods as $v) {
				$selected[] = $v['id']*1;
			}
		}
		
		/* 商品列表 */
		$goodsList = M("DistributionShopGoods")->where(array('cid'=>$this->aid, 'status'=>1))->getField("id,name,price,status");
		
        /* 运费模板 */		
		$deliveryTpl = M("DeliveryTpl")->where(array("cid" => $this->aid))->getField("id,name");
		$deliveryTplOptions = array( '0' => '==不使用运费模板==' );
		foreach ( $deliveryTpl as $k => $v ) $deliveryTplOptions[$k] = $v;
		$deliveryTplJson = json_encode((object)$deliveryTplOptions);
		$this->assign("deliveryTplJson", $deliveryTplJson);
		
		/* 代理级数 */
		$levels = array();
	    for( $i=0; $i<$agentLevel; $i++) {
	        $levels[$i] = $i+1;
	    }
		$this->assign("agentLevelJson", json_encode((object)$levels));
		
		$this->assign("goodsList", json_encode($goodsList));
		$this->assign("shippingMethods", json_encode((object)GoodsModel::$SHIPPING_METHOD));
		$this->assign("deliveryMethods", DeliveryModel::$METHOD);
		$this->assign("packageTypesOptions", Form::getOption(DistributionShopPackageModel::$packageTypes, "", '==请选择套餐类型=='));
		$this->assign("goodsPackage", json_encode($distributionShopPackage));
		$this->assign('selectedJson', json_encode($selected)); 
		$this->display('save');
	}
	
	/**
	 * 提交修改
	 * @see \Utuo\BackgroundController::submitPost()
	 */
	public function submitPost($model) {
		$model = is_object($model) ? $model : D($model);
		$goods = I("goods");
		if ( $model->create() ) {
			if ( empty($_REQUEST['id']) ) {
				unset($model->id);
				$id = $model->add();
				if ( $id ) {
					$this->savePackageGoods($id, $goods);
					$this->ajaxSuccess("添加成功！");
				} else {
					$this->ajaxError("添加失败！" . $model->getError() . $model->getLastSql());
				}
			} else {
				$id = $model->id;
				if (false !== $model->save()) {
					$this->savePackageGoods($id, $goods);
					$this->ajaxSuccess("修改成功！");
				} else {
					$this->ajaxError("修改失败！");
				}
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
	/**
	 * 保存套餐内商品
	 * @param unknown $packageId
	 * @param unknown $goods
	 */
	public function savePackageGoods( $packageId, $subGoods = array() ) {
		 $m = M("DistributionShopPackageGoods");
		 $goods = $m->where(array('packageId' => $packageId, 'cid' => $this->aid))->getField('goodsId,id,packageId,count');
		 $dbGoodsId = array_keys($goods);
		 $goodsId = array();
		 $addData = array();
		 foreach ( $subGoods as $k => $v ) {
		 	$goodsId[] = $v['id'];
		 	if ( !in_array($v['id'], $dbGoodsId)) {
		 		$addData[] = array(
		 			'packageId' => $packageId,
		 			'goodsId' => $v['id'],
		 			'count' => $v['count']*1,
		 		);
		 	} else {
		 		$m->where("packageId=%d and goodsId=%d", $packageId, $v['id'])->save(array(
		 			'count' => $v['count']*1,
		 		));
		 	}
		 }
		 $addData and $m->addAll($addData);
		 $delIds = array_diff($dbGoodsId, $goodsId) and $m->where(array('packageId' => $packageId, 'goodsId' => array('in', array_values($delIds)) ))->delete();
	}
	
	public function setSortAction() {
		$id = I('id', 0, 'intval');
		$sort = I('sort', 0, 'intval');
		M('DistributionShopPackage')->where(array('id'=>$id, 'cid'=>$this->aid))->setField('sort', $sort);
	}
	
}